#include <iostream>
#include <stdio.h>
#include "ClientBootstrap.h"
#include "Log.h"
#include "Codec.h"
#include "ReactorThread.h"

using namespace dsth;

class ChatClient {
public:
    ChatClient(EventLoop* loop, const InetSocketAddress& addr, const char* name) 
        : client_(loop, addr, name), name_(name), conn_(NULL) {
        client_.SetOnConnection(std::make_pair(this, &ChatClient::OnConnect));
        client_.SetOnMessage(std::make_pair(&codec_, &Codec::OnMessage));
        client_.SetOnDisConnection(std::make_pair(this, &ChatClient::OnDisConnect));
        codec_.SetMessageHandler(std::make_pair(this, &ChatClient::OnMessage));
    }
    void Run() { client_.Connect(); }
    void Stop() {
        // TODO:
    }
    void Send(string& text) {
        size_t pos = text.find_first_of('@');
        message_t msg;
        msg.to.assign(text, 0, pos);
        msg.from.assign(name_);
        msg.chat_text.assign(text, pos + 1, text.size());
        codec_.SendMessage(conn_, msg);
    }
    void OnConnect(Connection* conn) {
        printf("connected to chat server\n");
        conn_ = conn;
        message_t msg;
        msg.to.assign("LOGIN");
        msg.from.assign(name_);
        codec_.SendMessage(conn, msg);
    }

    void OnMessage(Connection* conn, message_t* msg, Timestamp time) {
        printf("TO:%s, FROM:%s, Text:%s\n", msg->to.c_str(), msg->from.c_str(), msg->chat_text.c_str());
    }

    void OnDisConnect(Connection* conn) {

    }

private:
    ClientBootstrap client_;
    string name_;
    Connection* conn_;
    Codec codec_;
    
};

int main(int argc, char** argv) {
    if (argc != 2) { 
        printf("Usage: Name\n");
        return -1;
    }
#ifdef IS_WINDOWS
    WSADATA wsaData;
    int err = WSAStartup( MAKEWORD(2,2), &wsaData );
    if( err != NO_ERROR )
        printf("Error at WSAStartup\n");
#endif

    NewLogger("./chat_client.log", Logger::E_DEBUG);
    string name(argv[1]);
    ReactorThread thread;
    InetSocketAddress addr("127.0.0.1", 10084);

    ChatClient client(thread.Run(), addr, name.c_str());
    client.Run();

    std::string line;
    while (std::getline(std::cin, line)) {
        string message(line.c_str());
        client.Send(message);
    }

    client.Stop();
#ifdef IS_WINDOWS
    WSACleanup();
#endif
    return 0;
}
